<?php

/**
 * Name:
 * User: Silent
 * Date: 2025-09-25
 * Time: 22:31:12
 */

namespace App\Services\Auth;

use App\Services\Auth\JwtService;
use App\Repositories\Auth\WechatUserRepository;
use App\Repositories\Config\EmployeeRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;

class LoginService
{
    public $wechatUserRepository;
    public $employeeRepository;

    public function __construct(
        WechatUserRepository $wechatUserRepository,
        EmployeeRepository $employeeRepository
    ) {
        $this->wechatUserRepository = $wechatUserRepository;
        $this->employeeRepository = $employeeRepository;
    }

    /**
     * @param mixed $code
//     * @throws InvalidConfigException
     * @throws Exception
     */
    public function wxLogin($code)
    {
        $wxService = new WxService();
        $response  = $wxService->getUserSession($code);
        if (isset($response['errcode'])) {
            return ['success' => false, 'message' => $response['errmsg']];
        }

        $wxUserInfo = $this->wechatUserRepository->createOrUpdate([
            'openid'      => $response['openid'],
            'session_key' => $response['session_key'],
            'created_at'  => date('Y-m-d H:i:s'),

        ]);

        $wxUserInfo          = $wxUserInfo->toArray();
        $wxUserInfo['token'] = JwtService::createToken($wxUserInfo['id']);

        return ['success' => true, 'data' => $wxUserInfo, 'message' => ''];
    }

    public function setUserInfo($post)
    {
        $wxUserInfo = $this->wechatUserRepository->findByOpenid($post['openid']);
        if (empty($wxUserInfo)) {
            return ['success' => false, 'message' => '用户不存在'];
        }

        $updateData = [];
        if (!empty($post['avatarUrl'])) {
            $updateData['headimgurl'] = $post['avatarUrl'];
        }
        if (!empty($post['nickname'])) {
            $updateData['nickname'] = $post['nickname'];
        }

        if (!empty($updateData)) {
            $this->wechatUserRepository->updateByOpenid($post['openid'], $updateData);
        }

        return ['success' => true, 'data' => '', 'message' => ''];
    }

    public function refreshToken($openId)
    {
        $userInfo = $this->wechatUserRepository->findByOpenid($openId);
        if (!$userInfo) {
            return ['success' => false, 'message' => '用户不存在'];
        }

        $token = JwtService::createToken($userInfo->id);
        $userInfo->token = $token;

        return ['success' => true, 'data' => $userInfo, 'message' => ''];
    }

    public function getUserInfo($id)
    {
        $userInfo = $this->wechatUserRepository->find($id);
        if (!$userInfo) {
            return ['success' => false, 'message' => '用户不存在'];
        }

        return ['success' => true, 'data' => $userInfo, 'message' => ''];
    }

    /**
     * 更新员工公司和部门信息
     *
     * @param string $openid
     * @param string $company  
     * @param string $department
     * @return array
     */
    public function updateEmployeeCompanyInfo($openid, $company, $department)
    {
        try {
            DB::beginTransaction();

            // 通过openid查找微信用户
            $wechatUser = $this->wechatUserRepository->findByOpenid($openid);
            if (!$wechatUser) {
                DB::rollBack();
                return [
                    'success' => false,
                    'message' => '微信用户不存在，请先登录'
                ];
            }

            // 查找绑定的员工
            $employee = $this->employeeRepository->query()
                ->where('wechat_user_id', $wechatUser->id)
                ->first();

            if (!$employee) {
                DB::rollBack();
                return [
                    'success' => false,
                    'message' => '该微信用户尚未绑定员工信息，请先进行员工绑定'
                ];
            }

            // 更新员工的公司和部门信息
            $updateData = [
                'company' => $company,
                'department' => $department,
                'updated_at' => now()
            ];

            $employee->update($updateData);

            DB::commit();

            Log::info('员工公司部门信息更新成功', [
                'employee_id' => $employee->id,
                'employee_name' => $employee->name,
                'company' => $company,
                'department' => $department,
                'openid' => $openid
            ]);

            return [
                'success' => true,
                'message' => '公司部门信息更新成功',
                'data' => [
                    'employee_id' => $employee->id,
                    'employee_name' => $employee->name,
                    'company' => $company,
                    'department' => $department,
                    'team' => $employee->team,
                    'position' => $employee->position,
                    'updated_at' => $employee->updated_at->format('Y-m-d H:i:s')
                ]
            ];

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error('更新员工公司部门信息失败', [
                'error' => $e->getMessage(),
                'openid' => $openid,
                'company' => $company,
                'department' => $department
            ]);

            return [
                'success' => false,
                'message' => '更新失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 更新微信用户的公司和部门信息，如果有绑定员工则同步更新
     *
     * @param object $wechatUser 微信用户对象
     * @param string $company 公司名称
     * @param string $department 部门名称
     * @return array
     */
    public function updateWechatUserCompanyInfo($wechatUser, $company, $department)
    {
        try {
            DB::beginTransaction();

            if (!$wechatUser) {
                DB::rollBack();
                return [
                    'success' => false,
                    'message' => '微信用户信息不存在'
                ];
            }

            // 更新微信用户的公司和部门信息
            $updateData = [
                'company' => $company,
                'department' => $department,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            $wechatUser->update($updateData);

            // 查找是否有绑定的员工
            $employee = $this->employeeRepository->query()
                ->where('wechat_user_id', $wechatUser->id)
                ->first();

            // 如果有绑定员工，同步更新员工表的公司和部门信息
            if ($employee) {
                $employee->update([
                    'company' => $company,
                    'department' => $department,
                ]);

                Log::info('微信用户和员工公司部门信息更新成功', [
                    'wechat_user_id' => $wechatUser->id,
                    'employee_id' => $employee->id,
                    'employee_name' => $employee->name,
                    'company' => $company,
                    'department' => $department
                ]);
            } else {
                Log::info('微信用户公司部门信息更新成功（无绑定员工）', [
                    'wechat_user_id' => $wechatUser->id,
                    'openid' => $wechatUser->openid,
                    'company' => $company,
                    'department' => $department
                ]);
            }

            DB::commit();

            // 构建返回数据
            $responseData = [
                'wechat_user_id' => $wechatUser->id,
                'openid' => $wechatUser->openid,
                'nickname' => $wechatUser->nickname,
                'company' => $company,
                'department' => $department,
                'is_bound' => !empty($employee),
                'updated_at' => $wechatUser->updated_at
            ];

            // 如果有绑定员工，添加员工信息
            if ($employee) {
                $responseData['employee'] = [
                    'id' => $employee->id,
                    'name' => $employee->name,
                    'team' => $employee->team,
                    'position' => $employee->position,
                ];
            }

            return [
                'success' => true,
                'message' => '公司部门信息更新成功',
                'data' => $responseData
            ];

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error('更新微信用户公司部门信息失败', [
                'error' => $e->getMessage(),
                'wechat_user_id' => $wechatUser->id ?? null,
                'company' => $company,
                'department' => $department
            ]);

            return [
                'success' => false,
                'message' => '更新失败：' . $e->getMessage()
            ];
        }
    }

    /**
     * 通过员工对象直接更新公司和部门信息（用于认证后的验证）
     * @deprecated 此方法已废弃，请使用 updateWechatUserCompanyInfo
     *
     * @param object $employee
     * @param string $company
     * @param string $department
     * @return array
     */
    public function updateEmployeeCompanyInfoByEmployee($employee, $company, $department)
    {
        try {
            DB::beginTransaction();

            if (!$employee) {
                DB::rollBack();
                return [
                    'success' => false,
                    'message' => '员工信息不存在'
                ];
            }

            // 更新员工的公司和部门信息
            $updateData = [
                'company' => $company,
                'department' => $department,
                'updated_at' => now()
            ];

            $employee->update($updateData);

            DB::commit();

            Log::info('员工公司部门信息更新成功（通过认证）', [
                'employee_id' => $employee->id,
                'employee_name' => $employee->name,
                'company' => $company,
                'department' => $department,
                'wechat_user_id' => $employee->wechat_user_id
            ]);

            return [
                'success' => true,
                'message' => '公司部门信息更新成功',
                'data' => [
                    'employee_id' => $employee->id,
                    'employee_name' => $employee->name,
                    'company' => $company,
                    'department' => $department,
                    'team' => $employee->team,
                    'position' => $employee->position,
                    'updated_at' => $employee->updated_at->format('Y-m-d H:i:s')
                ]
            ];

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error('更新员工公司部门信息失败（通过认证）', [
                'error' => $e->getMessage(),
                'employee_id' => $employee->id ?? null,
                'company' => $company,
                'department' => $department
            ]);

            return [
                'success' => false,
                'message' => '更新失败：' . $e->getMessage()
            ];
        }
    }
}
